import styled from '@emotion/styled';
import { Skeleton, Tree, TreeDataNode } from 'antd';
import { FC } from 'react';

import { usePost } from '@/api';
import PlusIcon from '@/assets/icons/plus.svg';
import { colors } from '@/config/theme';
import { emitter } from '@/utils/emitter';

import { CategoryModifyForm } from './category-modify-form';
import { CategoryMore } from './category-more';
import { FlowMore } from './flow-more';
import { GroupMore } from './group-more';
import { TreeNodeItem } from './tree-node-item';

const TreeStyled = styled(Tree)`
  height: 100%;
  .ant-tree-switcher {
    display: flex;
    align-items: center;
    justify-content: center;
  }
`;

export const FlowList: FC = memo(() => {
  const { loading, data: categoryList, refresh } = usePost('/group/listWithCategory', {});
  const push = useNavigate();
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [searchParams] = useSearchParams();

  const treeData: TreeDataNode[] =
    categoryList?.map((category) => {
      return {
        title: (
          <TreeNodeItem
            icon={category.icon}
            title={category.name}
            onClick={() => {
              setExpandedKeys([category.id!.toString()]);
            }}
            right={
              <CategoryMore
                type="add"
                refresh={refresh}
                onAddSuccess={(newFlowId: number) => {
                  push('?flowId=' + newFlowId);
                }}
                cateGoryInfo={{
                  name: category.name!,
                  icon: category.icon!
                }}
                categoryId={category.id!}
              />
            }
          />
        ),
        selectable: false,
        key: String(category.id!),
        children: category.groups?.map((group) => {
          return {
            title: (
              <TreeNodeItem
                title={group.name}
                onClick={() => {
                  setExpandedKeys([category.id!.toString(), [category.id, group.id].join('-')]);
                  const [first] = group.flows || [];
                  if (first) {
                    push('?flowId=' + first.id);
                  }
                }}
                right={<GroupMore refresh={refresh} group={group.id!} groupName={group.name!} groupDesc={group.desc!} />}
              />
            ),
            selectable: false,
            key: [category.id, group.id].join('-'),
            children: group.flows?.map((flow) => {
              return {
                title: (
                  <TreeNodeItem
                    onClick={() => {
                      push('?flowId=' + flow.id);
                    }}
                    isActive={flow.id === Number(searchParams.get('flowId'))}
                    title={`${flow.flowName} (${flow.versionNo})`}
                    right={<FlowMore flowId={flow.id!} refresh={refresh} />}
                  />
                ),
                key: [category.id, group.id, flow.id].join('-')
              };
            })
          };
        })
      };
    }) || [];

  useEffect(() => {
    emitter.on('refresh-flow-list', refresh);

    return () => {
      emitter.off('refresh-flow-list', refresh);
    };
  }, [refresh]);

  useEffect(() => {
    const flowId = searchParams.get('flowId');
    if (flowId) {
      categoryList?.find((category) => {
        return category.groups?.find((group) => {
          return group.flows?.find((flow) => {
            if (flow.id === Number(flowId)) {
              setExpandedKeys([String(category.id), `${category.id}-${group.id}`]);
              return true;
            }
            return false;
          });
        });
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [categoryList]);

  return (
    <div className="flow-list h-full">
      <div className="flex justify-between items-center h-40 px-12 bg-gray-100">
        <div className="text-14--bold ">决策列表</div>
        <CategoryModifyForm type="add" refresh={refresh}>
          <div className="flex items-center cursor-pointer">
            <PlusIcon className="w-14 h-14" fill={colors.primary[500]} />
            <span className="text-14 text-primary-500 ml-4">新增场景</span>
          </div>
        </CategoryModifyForm>
      </div>
      <Skeleton active loading={loading}>
        <TreeStyled
          expandedKeys={expandedKeys}
          onExpand={(keys) => {
            setExpandedKeys(keys as string[]);
          }}
          blockNode
          showIcon
          showLine
          treeData={treeData}
        />
      </Skeleton>
    </div>
  );
});
